package main

import (
	"bytes"
	"github.com/playnb/mustang/global"
	"github.com/playnb/mustang/log"
	"github.com/playnb/mustang/utils"
	"github.com/playnb/mustang/weixin"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"text/template"
	"time"
)

func substr(s string, pos, length int) string {
	runes := []rune(s)
	l := pos + length
	if l > len(runes) {
		l = len(runes)
	}
	return string(runes[pos:l])
}
func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Error(err.Error())
	}
	return strings.Replace(dir, "\\", "/", -1)
}
func getParentDirectory(dirctory string) string {
	return substr(dirctory, 0, strings.LastIndex(dirctory, "/"))
}

var baseDir = getParentDirectory(getCurrentDirectory()) + "/src/github.com/playnb/grasslands/"

var indexTemplate = template.Must(template.New("").Parse(`
    <!--server_replace_start-->
    <script>
    	egret.wxShareName = "{{.ShareName}}"
    	
    	egret.wxOpenID = "{{.OpenID}}"
		egret.wxUserName = "{{.UserName}}"
		egret.wxPic = "{{.Pic}}"
		
		egret.wxAccessToken = "{{.Token}}"
		
		egret.wxAppId = "{{.AppId}}"
		egret.wxTimeStamp = {{.TimeStamp}}
		egret.wxNonce = "{{.Nonce}}"
		egret.wxSignature = "{{.Signature}}"
		
		//"http://liutp.vicp.net/wx/authorize?state=1$shareOpenID=0"
		egret.wxShareURL = "http://{{.ShareURL}}/wx/authorize?state={{.AppName}}$shareOpenID={{.OpenID}}"
		
		
		var adsObject = new adwojs({
	    	eid:'spn', //节点id
	    	aid: 'a02b60151c254fb6b6bd9143a8059ee3', //申请的android平台pid
	    	pid: '63086d44091843538e764962f5022ce0', //申请的iphone平台pid
	    	bt: true, //是否开启测试广告，用于客户在申请PID过程中的广告测试,默认值为false
	    	af:true, //是否自动适合ipad平板广告，默认值为true。
	    	so: false,//是否在点击广告时，新开一个窗口，默认为false，表示不新开窗口
	    	dawx: false,//android下微信流量是否关闭，默认false，表示不关闭
	    	danwx: false,//android下非微信流量是否关闭，默认false，表示不关闭
	    	diwx: false,//ios下微信流量是否关闭，默认false，表示不关闭
	    	dinwx: false,//ios下非微信流量是否关闭，默认false，表示不关闭
	    	width: 270, //广告图片宽度(除320外，还有720宽度，用于ipad中显示)
	    	height: 50 //广告图片高度(除50外，还有110高度，用于ipad中显示)
    	});
    	
    	egret.AdsDiv = document.getElementById('spn')
    	egret.ShowAdvertiseBar = function(show, top){
			egret.AdsDiv.innerHTML=""
    		if(show){
    			egret.AdsDiv.visibility="visible"
    			egret.AdsDiv.style.position="absolute"
    			if (top){ 
    				egret.AdsDiv.style.top="0px"
    			}else{
    				egret.AdsDiv.style.bottom="0px"
    			}
    			adsObject.send();
    		}else{
    			egret.AdsDiv.innerHTML=""
    			egret.AdsDiv.visibility="hidden"
    		}
    	}
	</script>
    <!--server_replace_end-->
`))

//处理静态文件
func handleStatic(w http.ResponseWriter, r *http.Request) {

	requestPath := r.RequestURI
	prefix := "/apps"
	staticDir := "htdoc"

	timeStamp := strconv.Itoa(int(time.Now().UnixNano() / 1000 / 1000 / 1000))
	nonce := "wahaha"
	shareURL := global.C.ServiceDomain

	if strings.HasPrefix(requestPath, prefix) {
		params := strings.Split(requestPath, "/")
		tokenPrefix := "SC_"

		if len(params) == 4 && strings.HasPrefix(params[3], tokenPrefix) {
			pStr := params[3][len(tokenPrefix):]
			log.Debug("参数:%s", pStr)
			params[3] = "index.html"
			appName := params[2]
			requestPath = strings.Join(params, "/")
			file := path.Join(staticDir, requestPath[len(prefix):])
			log.Trace("读取文件" + file)

			fin, err := os.Open(file)
			defer fin.Close()
			if err != nil {
				log.Error("static resource: %v", err)
				http.NotFound(w, r)
			} else {
				fd, _ := ioutil.ReadAll(fin)
				fstr := string(fd)
				rp := regexp.MustCompile("<!--server_replace_start-->[\\s\\S]*<!--server_replace_end-->")
				fstr = rp.ReplaceAllStringFunc(fstr, func(str string) string {

					p := &utils.WinXinHttpParams{}
					err := p.Decode(pStr, "bacchus")
					if err != nil {
						return err.Error()
					} else {
						type __TemplateData struct {
							UserName  string
							ShareName string
							Pic       string
							OpenID    string
							Token     string
							AppId     string
							TimeStamp string
							Nonce     string
							Signature string
							AppName   string
							ShareURL  string
							MyURL     string
						}
						td := &__TemplateData{}
						td.UserName = p.UserName
						td.ShareName = p.ShareName
						td.Pic = p.Pic
						td.OpenID = p.OpenID
						td.Token = p.ServerToken
						td.AppId = global.C.AppID
						td.TimeStamp = timeStamp
						td.Nonce = nonce
						td.MyURL = "http://" + r.Host + r.RequestURI
						td.Signature = weixin.MakeSignature_js(timeStamp, nonce, weixin.Profile().JsApiTicket, td.MyURL)
						td.AppName = appName
						td.ShareURL = shareURL
						var buf bytes.Buffer
						indexTemplate.Execute(&buf, td)
						log.Dev("ServerToken: %s", p.ServerToken)
						return buf.String()

						//TODO: 这个有空改成go模板
						templateStr := `
	    <!--server_replace_start-->
	    <script>
	    	egret.wxShareName = "{{.ShareName}}"
	    	
	    	egret.wxOpenID = "{{.OpenID}}"
			egret.wxUserName = "{{.UserName}}"
			egret.wxPic = "{{.Pic}}"
			
			egret.wxAccessToken = "{{.Token}}"
			
			egret.wxAppId = "{{.AppId}}"
			egret.wxTimeStamp = {{.TimeStamp}}
			egret.wxNonce = "{{.Nonce}}"
			egret.wxSignature = "{{.Signature}}"
			
			//"http://liutp.vicp.net/wx/authorize?state=1$shareOpenID=0"
			egret.wxShareURL = "http://{{.ShareURL}}/wx/authorize?state={{.AppName}}$shareOpenID={{.OpenID}}"
		</script>
	    <!--server_replace_end-->
						`
						templateStr = strings.Replace(templateStr, "{{.UserName}}", p.UserName, 1)
						templateStr = strings.Replace(templateStr, "{{.ShareName}}", p.ShareName, 1)
						templateStr = strings.Replace(templateStr, "{{.Pic}}", p.Pic, 1)
						templateStr = strings.Replace(templateStr, "{{.OpenID}}", p.OpenID, 2)
						templateStr = strings.Replace(templateStr, "{{.Token}}", p.Token, 1)

						templateStr = strings.Replace(templateStr, "{{.AppId}}", global.C.AppID, 1)
						templateStr = strings.Replace(templateStr, "{{.TimeStamp}}", timeStamp, 1)
						templateStr = strings.Replace(templateStr, "{{.Nonce}}", nonce, 1)
						templateStr = strings.Replace(templateStr, "{{.Signature}}", weixin.MakeSignature_js(timeStamp, nonce, weixin.Profile().JsApiTicket, "http://"+r.Host+r.RequestURI), 1)

						templateStr = strings.Replace(templateStr, "{{.AppName}}", appName, 1)
						templateStr = strings.Replace(templateStr, "{{.ShareURL}}", shareURL, 1)

						log.Debug("替换的模板\n" + templateStr)
						return templateStr
					}
				})
				w.Write([]byte(fstr))
			}
		} else {
			index := len(prefix)
			fileName := requestPath[index:]
			file := path.Join(staticDir, fileName)
			//log.Debug("读取文件" + file)
			w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
			http.ServeFile(w, r, file)
		}
	} else {
		http.NotFound(w, r)
	}
}
